const { getConnection } = require('../config/db');

class CommentModel {
  // 添加评论
  static async addComment(openid, videoId, content) {
    const connection = await getConnection();
    try {
      // 简单敏感词过滤（实际项目中应该使用更完善的敏感词库）
      const filteredContent = content.replace(/傻逼|垃圾|fuck|shit/gi, '**');
      
      const sql = 'INSERT INTO comments (openid, video_id, content) VALUES (?, ?, ?)';
      const [result] = await connection.execute(sql, [openid, videoId, filteredContent]);
      
      return {
        id: result.insertId,
        openid,
        video_id: videoId,
        content: filteredContent,
        created_at: new Date()
      };
    } finally {
      connection.release();
    }
  }

  // 获取视频评论列表
  static async getCommentsByVideoId(videoId, page = 1, pageSize = 20) {
    const connection = await getConnection();
    try {
      const pageNum = Number.isFinite(Number(page)) ? Number(page) : 1;
      const pageSizeNum = Number.isFinite(Number(pageSize)) ? Number(pageSize) : 20;
      const offset = (pageNum - 1) * pageSizeNum;
      
      const sql = `
        SELECT * FROM comments 
        WHERE video_id = ? 
        ORDER BY created_at DESC 
        LIMIT ${pageSizeNum} OFFSET ${offset}
      `;
      
      const [rows] = await connection.execute(sql, [videoId]);
      
      const countSql = 'SELECT COUNT(*) as total FROM comments WHERE video_id = ?';
      const [countResult] = await connection.execute(countSql, [videoId]);
      
      return {
        list: rows,
        total: countResult[0].total,
        page: pageNum,
        pageSize: pageSizeNum
      };
    } finally {
      connection.release();
    }
  }

  // 获取最近评论（全局）
  static async getRecentComments(limit = 10) {
    const connection = await getConnection();
    try {
      const limitNum = Number.isFinite(Number(limit)) ? Number(limit) : 10;
      const sql = `
        SELECT c.*, v.title as video_title
        FROM comments c
        LEFT JOIN videos v ON c.video_id = v.id
        ORDER BY c.created_at DESC
        LIMIT ${limitNum}
      `;
      const [rows] = await connection.execute(sql);
      return rows;
    } finally {
      connection.release();
    }
  }
}

module.exports = CommentModel;